package com.novunda.platform.security;

import com.novunda.platform.common.utils.StringUtil;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @author linfeng
 * @since 2016/8/29
 */
public class SystemFormAuthenticationFilter extends CommonAuthenticationFilter {

    private static final Logger log = LoggerFactory.getLogger(SystemFormAuthenticationFilter.class);

    private String usernameParam = "username";
    private String passwordParam = "password";
    private String rememberMeParam = "rememberMe";

    public SystemFormAuthenticationFilter(String loginUrl) {
        setLoginUrl(loginUrl);
    }

    public SystemFormAuthenticationFilter() {
    }

    public String getUsernameParam() {
        return usernameParam;
    }

    public void setUsernameParam(String usernameParam) {
        this.usernameParam = usernameParam;
    }

    public String getPasswordParam() {
        return passwordParam;
    }

    public void setPasswordParam(String passwordParam) {
        this.passwordParam = passwordParam;
    }

    public String getRememberMeParam() {
        return rememberMeParam;
    }

    public void setRememberMeParam(String rememberMeParam) {
        this.rememberMeParam = rememberMeParam;
    }

    protected boolean isRememberMe(ServletRequest request) {
        return WebUtils.isTrue(request, getRememberMeParam());
    }

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {


        logout(request, response);

        String username = getUsername(request);
        String password = getPassword(request);
        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)){
            throw new LoginException("用户名或密码不能为空");

        }
//        // 判断是否是admin账户
        if (!username.equals("admin")) {
            throw new LoginException("用户名或密码错误");
        }
        if (password == null) {
            password = "";
        }
        boolean rememberMe = isRememberMe(request);
        String host = getHost(request);

        return new NovUsernamePasswordToken(username, password.toCharArray(), rememberMe, host, LoginTypeEnum.FORM);

    }

    protected String getUsername(ServletRequest request) {
        return WebUtils.getCleanParam(request, getUsernameParam());
    }

    protected String getPassword(ServletRequest request) {
        return WebUtils.getCleanParam(request, getPasswordParam());
    }

}
